/*
* --------------------------------------
* Functions that manipulates the objects
* CRUD, Search
* --------------------------------------
* 
* nomenclature
* ------------
* display+...: write in the DOM
*
*/

function IC($scope)
{
	$scope.items = [{text:'first thing'}];
}

function IM()
{
	// singleton
	if ( IM.prototype._singletonInstance ) {
	      return IM.prototype._singletonInstance;
	}
	IM.prototype._singletonInstance = this;
	
	var page = null; // indicate the current page (m: ulist)
	var sortBy = 'distance'; // kind of object sortin
	var items = []; // "items" array, contains all the "item" objects
	
	var imgURL = new Array(); // contain all the url of the pictures uploaded
	var img = new Array();
	
	this.set_imgURL = function(fileName)
	{
		imgURL.push(fileName);		
	};
	
	/*
	 *  PUBLIC
	 */
	
	this.getItems = function()
	{
		return items;
	};
	
	/*
	 *  PUBLIC
	 *  Change the current page value
	 */
	this.set_page = function(newPage)
	{
		page = newPage;
	};
	
	/*
	 * PRIVATE
	 * Get data frIM item(s) the BDD in a JSON format
	 */
	this.get = function(mode, id, bounds) 
	{
		switch(mode)
		{
			// load object with geographical bounds
			case 'bounds' : url = '/'+BASEPATH+'I/get_bounds/'; var data = bounds; break;
			// load only user item
			// id is here the uid
			case 'user' : url = '/'+BASEPATH+'I/get_items/user/'+id; break;
			// load only one iten
			case 'item' : url = '/'+BASEPATH+'I/get_item/'+id; break;
		}
		
		$.ajax({
			type: 'POST',
			url: url,
			data: { data : data },
			timeout: 3000,
			success: function(data)
			{
				switch(mode)
				{
					case 'bounds' : onGetItems(data); break;
					case 'user' : onGetItems(data); break;
					case 'item' : onGetItem(data); break;
				}
			},
			error: function() { display_alert('connexion problem', '#alert_area', 'error'); console.log('get(): error'); }
		});
	};
	
	/*
	 *  PRIVATE
	 *  Empty and update the array 'items' from JSON formatted data
	 *  data : JSON format
	 */
	function push(data)
	{
		MM.clearLayer_items(); // clear the items layer of the map before adding new items
		$.each(data, function(index, array) // create the array, index count the iterations, array is the content
		{
			
			var id = array['id'];
			var item = new Item(array); // create an item and give it the array with the content
			items[id] = item; // the associative array "items" collects all the items by id
			//IC.items.push({text:item.name});
			onPush(item);
		});
		
		console.log('pushItem(): success');
	};
	
	/*
	 * PRIVATE
	 * Create an item in the BDD
	 */
	this.create = function() {
		
		var registrationMarker = MM.get_registrationMarker();
		
		//debugger;
		var title = $('#title').val();
	    var price = $('#price').val();
	    var description = $('#description').val();
	    var lat = registrationMarker.getLatLng().lat;
	    var lng = registrationMarker.getLatLng().lng;
	    var terms = $('#terms').val();

	    if(imgURL == null)
	    	{ img = 'empty'; }
	    else
	    	{ img = imgURL.toString(); }

	    console.log(imgURL);
	    
		$.ajax({
			type: 'POST',
			url: 'object/create',
			data: {'title': title, 'description': description, 'lat': lat, 'lng': lng, 'terms' : terms, 'imgURL': img},
			timeout: 3000,
			success: function(data) {
				if(data == 'success')
				{
					onCreated();
		    		display_alert('The item has been added', '#alert_area', 'success');
				}
				else if(data == 'fail_login')
				{
					display_alert('You must be logged to add an item', '#alert_area', 'error');
				}
				else if(data == 'fail_form')
				{
					display_alert('You wrote something wrong', '#alert_area', 'error');
				}
				else
				{
					display_alert('The item hasn\'t been added', '#alert_area', 'error');
				}
			},
	        error: function() { display_alert('connexion problem', '#alert_area', 'error'); }
		});
		
		// reset the array containing the url of the uploaded picture
		imgURL.length = 0;
		//imgURL = null;
	};
	
	

/*
 *Update object 
 */

	this.init_update = function(thing_id) {
	
		var thing = IM.items[thing_id];
		
		// leaflet
		cancel_onMoveEnd();
		if(thing.marker != null)
		{
			thing.marker.unbindPopup();
			thing.marker.bindPopup('You can now move your object!').openPopup();
			thing.marker.dragging.enable();
		}
		//debugger;
		//display the form
		msg = '<img class="photo-medium img-polaroid" src="assets/uploads/'+displayPhoto(thing.uid, thing.imgURL)+'">'
		+ '<form id="form_object_update" method="post" accept-charset="utf-8" >'
		+ '	<label>Title</label><input type="text" id="title" name="title" value="'+thing.title+'" size="30" />'
		+ '	<label>Price</label><input type="text" id="price" name="price" value="'+thing.price+'" size="30" />' 
		+ '	<label>Description</label><textarea id="description" name="description">'+thing.description+'</textarea><br/>'
		+ ' 	<button type="submit" class="btn btn-primary" onclick="object_update('+thing.id+');return false;">Save changes</button>'
		+ ' 	<button type="button" class="btn" onclick="cancel_update('+thing.id+');return false;">Cancel</button>'
		+ '</form>';
		
		$('#'+thing.id).html(msg);
	};

	this.cancel_update = function(thing_id)
	{
		var thing = IM.items[thing_id];
		
		// leaflet
		init_onMoveEnd();
		
		thing.marker.closePopup();
		thing.marker.dragging.disable();
		
		displayList(items, 'distance');
	};

	
/*
 * Update an object
 */	
	
	this.update = function(id) {

		var item = items[id];
		
		var data=[];
		
		data['title'] = $('#title').val();
	    data['price'] = $('#price').val();
	    data['description'] = $('#description').val();
	    data['lat'] = item.marker.getLatLng().lat;
	    data['lng'] = item.marker.getLatLng().lng;
	    
	    if(imgURL == null || imgURL.length === 0)
	    	{ img = 'empty'; }
	    else
	    	{ img = imgURL.toString(); }
	    
	    // status
	    switch(item.update(data))
		{
	    	case 'success' :
	    		onUpdate();
	    		IM.get();
	    		/*registrationMarker.closePopup();
    			registrationLayer.clearLayers();*/
	    		IMC.cancel_create();
	    		display_alert('The item has been added', '#alert_area', 'success');
	    	break;
	    	case 'fail_login' :
				display_alert('You must be logged to add an item', '#alert_area', 'error');
			break;
	    	case 'fail_form' :
				display_alert('You wrote something wrong', '#alert_area', 'error');
	    	case 'connection' :
	    		display_alert('connexion problem', '#alert_area', 'error');
			break;
	    	default :
				display_alert('The item hasn\'t been added', '#alert_area', 'error');
		}
	};
	
/*
 * Delete an object
 */

	this.set_delete = function(thing_id)
	{
		$('#'+ thing_id).attr('status', 'delete');
	};

	this. init_delete = function()
	{
		$('[status="delete"]').each(function(i, e) {
			object_delete($(e).attr('id'));
		});
	};

	function object_delete(id)
	{
		$.ajax({
			type: 'GET',
			url: 'I/delete/'+id,
			timeout: 3000,
			success: function(data) {
			if(data == 'success')
			{
				display_alert('the item has been deleted', '#alert_area', 'success');
				IM.get();
				displayList(sortBy);
			}
			else
			{
				display_alert('the item hasn\'t been deleted', '#alert_area', 'error');
			}
		},
	        error: function() { display_alert('connexion problem', '#alert_area', 'error'); }
		});
	};

/*
 * Search an object
 */

	this.object_search = function(string) {
		
		if(IM.page == 'm')
		{
			domElem = '#mobject_list';
		}
		else
		{
			domElem = '#object_list';
		}
		
		
		$.ajax({
			type: 'POST',
			url: 'I/search',
			data: {'string': string, 'param': IM.page},
			timeout: 3000,
			success: function(data) {
				$(domElem).empty();
				if(!jQuery.isEmptyObject(data) && data != 'fail_form')
		    	{
					IM.updateitems(data);
					displayList(IM.sortBy);
					displayOnMap;
		    	}
		    	else
		    	{
		    		$(domElem).html('not found...');
		    	}
			},
	        error: function(data) { display_alert('connexion problem', '#alert_area', 'error'); }
		});
	};
	
	/*
	 * PUBLIC
	 * Refresh distance for items
	 *//*
	this.refreshDistance = function(mapCenter)
	{
		for(i in items)
		{
			// update distance in the object
			items[i].setDistance(mapCenter);
			*/
			// Else : display distance
			//$('#'+items[i].id+' .distance').html(displayDistance(items[i].distance));
		//}
		
		// If ordered by distance: display new distance and reorder list
		//displayList();
		/*console.log('refreshDistance() : success');
	};*/
	
	/*
	function displayListByPrice(selector)
	{
		sortBy = 'price';
		
		var array = [];
		
		// get the map center
		var mapCenter = map.getCenter();
		
		for(i in items)
		{
			items[i].setDistance(mapCenter);
			array.push([items[i], items[i].price]);
		}
		
		array.sort(function(a,b) { return a[1] - b[1]; });
		
		$(selector).empty();
		
		var priceCounter = 0;
		for(var i=0;i<array.length;i++)
		{
			var item = array[i][0];
			if(item.distance < MM.getPrecision() || page == 'm')
			{
				if(item.price>10 && item.price<50 && priceCounter<50 && i!=0)
				{
					$(selector).append('<div class="division"><strong>- 10 euros</strong></div>');
					priceCounter = 50;
				}
				if(item.price>50 && priceCounter<100 && i!=0)
				{
					$(selector).append('<div class="division"><strong>- 50 euros</strong></div>');
					priceCounter = 100;
				}
				
				var msg = displayListItem(item, page);
				$(selector).append(msg);
			}
		}
		$(selector).append('<div class="division"><strong>- '+displayDistance(MM.getPrecision())+'</strong></div>');
	}*/

	/*
	 * Event Listener
	 */
	
	function onGetItems(data)
	{
		// update the array
		// make sure we reset the array
		items = []; 
		// push all items retrieved
		push(data);
		
		switch(page)
		{
			case 'items' :
			// refresh list 
			IMC.displayList(items, sortBy);
			break;
			case 'user' :
			// refresh list 
			IMC.displayList(items, sortBy);
			break;
		}
		
		// display success message
		//display_alert('list updated', '#alert_area', 'success');
		console.log('get(): success');
	}
	
	function onGetItem(data)
	{	
		// push the item retrieved
		id = data['id'];
		var item = new Item(data); // create an item and give it the array with the content
		// display the tiem
		console.log('displayItem:'+ id);
		
		// push the object on the map
		MM.push(item);
		
		IMC.display(item);
	}
	
	function onPush(item)
	{
		// push the object on the map
		MM.push(item);
	}
	
	function onPop()
	{
		
	}
	
	function onUpdate()
	{
		
	}
	
	/*
	 * After an item has been added to the database
	 */
	function onCreated()
	{
		MM.refresh();
	}
	
	function onDelete()
	{
		
	}
}

console.log('IM loaded');